﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Telerik.Web.UI;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
using AjaxControlToolkit;

public partial class UserControl_uxMyAccountSettings : System.Web.UI.UserControl {
    protected void Page_Load(object sender, EventArgs e) {
        try {
            //setSecureProtocol(true);
            divName.Style.Add("Display", "None");
            divEmailNote.Style.Add("Display", "None");
            if (!IsPostBack) {
                Session["username"] = Membership.GetUser().UserName.ToString();
                BindAvailableList();
                selectUserName();
                FillCrdeitAmount();

                int tabIndex;
                if (!int.TryParse(Request.QueryString["tab"], out tabIndex)) tabIndex = 2;
                RadTabStrip1.SelectedIndex = tabIndex;
                RadMultiPage1.SelectedIndex = tabIndex;
            }

        } catch {
        }
    }
    public void setSecureProtocol(bool bSecure) {
        string redirectUrl = null;

        // if we want HTTPS and it is currently HTTP
        if (bSecure && !Request.IsSecureConnection)
            redirectUrl = Request.Url.ToString().Replace("http:", "https:");

        else

            // if we want HTTP and it is currently HTTPS
            if (!bSecure && Request.IsSecureConnection) redirectUrl = Request.Url.ToString().Replace("https:", "http:");

        //else

        // in all other cases we don't need to redirect

        // check if we need to redirect, and if so use redirectUrl to do the job
        if (redirectUrl != null)

            Response.Redirect(redirectUrl);

    }
    public void FillCrdeitAmount() {
        var credit = new DealesDataContext();
        var Amount = credit.GetCreditAmount(new Guid(Membership.GetUser().ProviderUserKey.ToString()));
        double money = 0.0;
        double referMoney = 0.0;
        CreditAmount.Text = "You have $" + money + " of Credit";
        foreach (var item in Amount) {
            if (item.amount != null) {
                money = Convert.ToDouble(item.amount.ToString());
                CreditAmount.Text = "You have $" + money + " of Credit";
                var referAmount = credit.GetReferAmount(new Guid(Membership.GetUser().ProviderUserKey.ToString()));
                foreach (var items in referAmount) {
                    if (items.ReferAmount != null) {
                        referMoney = Convert.ToDouble(items.ReferAmount.ToString());
                        CreditAmount.Text = "You have $" + (money - referMoney) + " of Credit";
                    }
                }
            }
        }


    }
    private void selectUserName() {

        var name = new DealesDataContext();
        var nameChangeQuery = name.Select_UserName(Membership.GetUser().ProviderUserKey.ToString());
        foreach (var item in nameChangeQuery) {
            if (item.LastName != null) {
                lblDisplayName.Text = item.FirstName.ToString() + " " + item.LastName.ToString();
                lblFullName.Text = item.FirstName.ToString() + " " + item.LastName.ToString();
            } else {
                lblDisplayName.Text = item.FirstName.ToString();
                lblFullName.Text = item.FirstName.ToString();
            }
            lblEmail.Text = item.Email.ToString();
            ViewState["UserID"] = item.UserId.ToString();
        }

    }
    public void GiftDLCouponsList_ItemDataBound(Object sender, DataListItemEventArgs e) {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
            LinkButton lnkBtnAsUsed = e.Item.FindControl("lnkBtnAsUsed") as LinkButton;
            LinkButton lblUsed = e.Item.FindControl("lblUsed") as LinkButton;
            bool used = Convert.ToBoolean(DataBinder.Eval(e.Item.DataItem, "Used"));
            if (!used) {
                lnkBtnAsUsed.Visible = true;
                lblUsed.Visible = false;
            } else {
                lnkBtnAsUsed.Visible = false;
                lblUsed.Visible = true;
            }
        }
    }
    public void DLCouponsList_ItemDataBound(Object sender, DataListItemEventArgs e) {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
            LinkButton lnkBtnAsUsed = e.Item.FindControl("lnkBtnAsUsed") as LinkButton;
            LinkButton lblUsed = e.Item.FindControl("lblUsed") as LinkButton;
            bool used = Convert.ToBoolean(DataBinder.Eval(e.Item.DataItem, "Used"));
            if (!used) {
                lnkBtnAsUsed.Visible = true;
                lblUsed.Visible = false;
            } else {
                lnkBtnAsUsed.Visible = false;
                lblUsed.Visible = true;
            }
        }
    }
    private void BindAvailableList() {
        try {
            ViewState["Type"] = "Available";
            var Deal = new DealesDataContext();
            var AvailableDeallist = Deal.Select_AvailableDealList(Session["username"].ToString());
            MyZupons.DataSource = AvailableDeallist;
            MyZupons.DataBind();
            if (MyZupons.Items.Count > 0) {
                MyZuponsError.Visible = false;
                MyZupons.Visible = true;
            } else {
                MyZuponsError.Visible = true;
                MyZupons.Visible = false;
                MyZuponsError.Text = "You do not have any Zupons voucher available.";
            }
            btnAvailable.ForeColor = System.Drawing.Color.Green;
        } catch (Exception ex) {
        }
    }
    protected void MyZupons_NeedDataSource(object source, GridNeedDataSourceEventArgs e) {
        try {
            var Deal = new DealesDataContext();
            if (ViewState["Type"].ToString() == "Available") {

                var AvailableDeallist = Deal.Select_AvailableDealList(Session["username"].ToString());
                MyZupons.DataSource = AvailableDeallist;
                MyZupons.DataBind();
                if (MyZupons.Items.Count > 0) {
                    MyZuponsError.Visible = false;
                    MyZupons.Visible = true;
                } else {
                    MyZuponsError.Visible = true;
                    MyZupons.Visible = false;
                    MyZuponsError.Text = "You do not have any Zupons voucher available.";
                }
            }
            if (ViewState["Type"].ToString() == "Used") {

                var AvailableDeallist = Deal.Select_UsedDealList(Session["username"].ToString());
                MyZupons.DataSource = AvailableDeallist;
                MyZupons.DataBind();
                if (MyZupons.Items.Count > 0) {
                    MyZuponsError.Visible = false;
                    MyZupons.Visible = true;
                } else {
                    MyZuponsError.Visible = true;
                    MyZupons.Visible = false;
                    MyZuponsError.Text = "You do not have any used Zupons.";
                }
            }
            if (ViewState["Type"].ToString() == "All") {
                var AvailableDeallist = Deal.Select_AllDealList(Session["username"].ToString());
                MyZupons.DataSource = AvailableDeallist;
                MyZupons.DataBind();
                if (MyZupons.Items.Count > 0) {
                    MyZuponsError.Visible = false;
                    MyZupons.Visible = true;
                } else {
                    MyZuponsError.Visible = true;
                    MyZupons.Visible = false;
                    MyZuponsError.Text = "You do not have any Zupons voucher available.";
                }
            }


        } catch {
        }
    }
    public void GiftDLCouponsList_DeleteCommand(object Source, DataListCommandEventArgs e) {
        Label CouponCodeID = (Label)(e.Item.FindControl("lblCouponCodeID"));
        var Deal = new DealesDataContext();
        var UpdateUsed = Deal.CouponCode_UsedUpdate(Convert.ToInt32(CouponCodeID.Text), Convert.ToBoolean(0));

        Label lblOrderID = (Label)(e.Item.FindControl("lblOrderID"));
        var CheckedUsed = Deal.CouponCode_CheckedUsedRecord(Convert.ToInt32(lblOrderID.Text));
        var UpdateOrderUsed = Deal.Order_UsedUpdate(Convert.ToInt32(lblOrderID.Text), Convert.ToBoolean(0));
        var Giftllist = Deal.Select_GiftList(Session["username"].ToString());
        Gift.DataSource = Giftllist;
        Gift.DataBind();


    }
    public void GiftDLCouponsList_EditCommand(object Source, DataListCommandEventArgs e) {
        Label CouponCodeID = (Label)(e.Item.FindControl("lblCouponCodeID"));
        var Deal = new DealesDataContext();
        var UpdateUsed = Deal.CouponCode_UsedUpdate(Convert.ToInt32(CouponCodeID.Text), Convert.ToBoolean(1));

        Label lblOrderID = (Label)(e.Item.FindControl("lblOrderID"));
        var CheckedUsed = Deal.CouponCode_CheckedUsedRecord(Convert.ToInt32(lblOrderID.Text));

        var UpdateOrderUsed = Deal.Order_UsedUpdate(Convert.ToInt32(lblOrderID.Text), Convert.ToBoolean(1));
        var Giftllist = Deal.Select_GiftList(Session["username"].ToString());
        Gift.DataSource = Giftllist;
        Gift.DataBind();
        if (Gift.Items.Count > 0) {
            MyGiftError.Visible = false;
            Gift.Visible = true;
        } else {
            Gift.Visible = false;
            MyGiftError.Visible = true;
            MyGiftError.Text = "You have not purchased any gifts at this time.";
        }
    }
    public void DLCouponsList_DeleteCommand(object Source, DataListCommandEventArgs e) {
        Label CouponCodeID = (Label)(e.Item.FindControl("lblCouponCodeID"));
        var Deal = new DealesDataContext();
        var UpdateUsed = Deal.CouponCode_UsedUpdate(Convert.ToInt32(CouponCodeID.Text), Convert.ToBoolean(0));

        //Label lblOrderID = (Label)(e.Item.FindControl("lblOrderID"));
        //var CheckedUsed = Deal.CouponCode_CheckedUsedRecord(Convert.ToInt32(lblOrderID.Text));
        //var UpdateOrderUsed = Deal.Order_UsedUpdate(Convert.ToInt32(lblOrderID.Text), Convert.ToBoolean(0));

        if (ViewState["Type"].ToString() == "Available") {

            var AvailableDeallist = Deal.Select_AvailableDealList(Session["username"].ToString());
            MyZupons.DataSource = AvailableDeallist;
            MyZupons.DataBind();
            if (MyZupons.Items.Count > 0) {
                MyZuponsError.Visible = false;
                MyZupons.Visible = true;
            } else {
                MyZupons.Visible = false;
                MyZuponsError.Visible = true;
                MyZuponsError.Text = "You do not have any Zupons voucher available.";
            }
        }
        if (ViewState["Type"].ToString() == "Used") {

            var AvailableDeallist = Deal.Select_UsedDealList(Session["username"].ToString());
            MyZupons.DataSource = AvailableDeallist;
            MyZupons.DataBind();
            if (MyZupons.Items.Count > 0) {
                MyZuponsError.Visible = false;
                MyZupons.Visible = true;
            } else {
                MyZupons.Visible = false;
                MyZuponsError.Visible = true;
                MyZuponsError.Text = "You do not have any used Zupons.";
            }
        }
        if (ViewState["Type"].ToString() == "All") {
            var AvailableDeallist = Deal.Select_AllDealList(Session["username"].ToString());
            MyZupons.DataSource = AvailableDeallist;
            MyZupons.DataBind();
            if (MyZupons.Items.Count > 0) {
                MyZuponsError.Visible = false;
                MyZupons.Visible = true;
            } else {
                MyZupons.Visible = false;
                MyZuponsError.Visible = true;
                MyZuponsError.Text = "You do not have any Zupons voucher available.";
            }
        }
    }
    public void DLCouponsList_EditCommand(object Source, DataListCommandEventArgs e) {
        Label CouponCodeID = (Label)(e.Item.FindControl("lblCouponCodeID"));
        var Deal = new DealesDataContext();
        var UpdateUsed = Deal.CouponCode_UsedUpdate(Convert.ToInt32(CouponCodeID.Text), Convert.ToBoolean(1));

        //Label lblOrderID = (Label)(e.Item.FindControl("lblOrderID"));
        //int OrderID = Convert.ToInt32(MyZupons.MasterTableView.DataKeyValues[0]["OrderID"]);
        // var CheckedUsed = Deal.CouponCode_CheckedUsedRecord(Convert.ToInt32(lblOrderID.Text));
        //int count = 0;
        //foreach (var item in CheckedUsed)
        //{
        //    count = Convert.ToInt32(item.NotUsedCount.ToString());
        //}
        //if (count == 0)
        //{
        //    var UpdateOrderUsed = Deal.Order_UsedUpdate(Convert.ToInt32(lblOrderID.Text), Convert.ToBoolean(1));
        //}
        if (ViewState["Type"].ToString() == "Available") {

            var AvailableDeallist = Deal.Select_AvailableDealList(Session["username"].ToString());
            MyZupons.DataSource = AvailableDeallist;
            MyZupons.DataBind();
            if (MyZupons.Items.Count > 0) {
                MyZuponsError.Visible = false;
                MyZupons.Visible = true;
            } else {
                MyZupons.Visible = false;
                MyZuponsError.Visible = true;
                MyZuponsError.Text = "You do not have any Zupons voucher available.";
            }
        }
        if (ViewState["Type"].ToString() == "Used") {

            var AvailableDeallist = Deal.Select_UsedDealList(Session["username"].ToString());
            MyZupons.DataSource = AvailableDeallist;
            MyZupons.DataBind();
            if (MyZupons.Items.Count > 0) {
                MyZuponsError.Visible = false;
                MyZupons.Visible = true;
            } else {
                MyZupons.Visible = false;
                MyZuponsError.Visible = true;
                MyZuponsError.Text = "You do not have any used Zupons.";
            }
        }
        if (ViewState["Type"].ToString() == "All") {
            var AvailableDeallist = Deal.Select_AllDealList(Session["username"].ToString());
            MyZupons.DataSource = AvailableDeallist;
            MyZupons.DataBind();
            if (MyZupons.Items.Count > 0) {
                MyZuponsError.Visible = false;
                MyZupons.Visible = true;
            } else {
                MyZupons.Visible = false;
                MyZuponsError.Visible = true;
                MyZuponsError.Text = "You do not have any Zupons voucher available.";
            }
        }
    }
    protected void btnAvailable_OnClick(object sender, EventArgs e) {
        try {

            btnAvailable.ForeColor = System.Drawing.Color.Green;
            btnAll.ForeColor = System.Drawing.Color.Blue;
            btnUsed.ForeColor = System.Drawing.Color.Blue;
            ViewState["Type"] = "Available";
            var Deal = new DealesDataContext();
            var AvailableDeallist = Deal.Select_AvailableDealList(Session["username"].ToString());
            MyZupons.DataSource = AvailableDeallist;
            MyZupons.DataBind();
            if (MyZupons.Items.Count > 0) {
                MyZuponsError.Visible = false;
                MyZupons.Visible = true;
            } else {
                MyZupons.Visible = false;
                MyZuponsError.Visible = true;
                MyZuponsError.Text = "You do not have any Zupons voucher available.";
            }
        } catch (Exception ex) {
        }

    }
    protected void btnUsed_OnClick(object sender, EventArgs e) {
        try {
            ViewState["Type"] = "Used";
            btnAvailable.ForeColor = System.Drawing.Color.Blue;
            btnAll.ForeColor = System.Drawing.Color.Blue;
            btnUsed.ForeColor = System.Drawing.Color.Green;
            var Deal = new DealesDataContext();
            var AvailableDeallist = Deal.Select_UsedDealList(Session["username"].ToString());
            MyZupons.DataSource = AvailableDeallist;
            MyZupons.DataBind();
            if (MyZupons.Items.Count > 0) {
                MyZuponsError.Visible = false;
                MyZupons.Visible = true;
            } else {
                MyZupons.Visible = false;
                MyZuponsError.Visible = true;
                MyZuponsError.Text = "You do not have any Used Zupons.";
            }

        } catch (Exception ex) {
        }

    }
    protected string TrimDescription(string description) {
        if (!string.IsNullOrEmpty(description) && description.Length > 70) {
            return string.Concat(description.Substring(0, 50), "...");
        }
        return description;
    }
    protected void btnAll_OnClick(object sender, EventArgs e) {
        try {
            ViewState["Type"] = "All";
            btnAvailable.ForeColor = System.Drawing.Color.Blue;
            btnAll.ForeColor = System.Drawing.Color.Green;
            btnUsed.ForeColor = System.Drawing.Color.Blue;
            var Deal = new DealesDataContext();
            var AvailableDeallist = Deal.Select_AllDealList(Session["username"].ToString());
            MyZupons.DataSource = AvailableDeallist;
            MyZupons.DataBind();
            if (MyZupons.Items.Count > 0) {
                MyZuponsError.Visible = false;
                MyZupons.Visible = true;
            } else {
                MyZupons.Visible = false;
                MyZuponsError.Visible = true;
                MyZuponsError.Text = "You do not have any Zupons voucher available.";
            }

        } catch (Exception ex) {
        }

    }
    protected void Gift_NeedDataSource(object source, GridNeedDataSourceEventArgs e) {
        try {
            var Deal = new DealesDataContext();
            var Giftllist = Deal.Select_GiftList(Session["username"].ToString());
            Gift.DataSource = Giftllist;
            if (Gift.Items.Count > 0) {
                MyGiftError.Visible = false;
                Gift.Visible = true;
            } else {
                Gift.Visible = false;
                MyGiftError.Visible = true;
                MyGiftError.Text = "You have not purchased any gifts at this time.";
            }
        } catch {
        }
    }
    protected void MyZupons_ItemDataBound(object sender, GridItemEventArgs e) {
        if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
        {
            var Deal = new DealesDataContext();


            Select_AvailableDealListResult dataItem = e.Item.DataItem as Select_AvailableDealListResult;
            if (dataItem != null)
            {
                Label lblVendor = e.Item.FindControl("lblVendor") as Label;
                var dealItem = Deal.Select_DealByID(dataItem.DealID);
                foreach (var selectDealByIdResult in dealItem)
                {
                    var vendor = Deal.Select_VendorByID(selectDealByIdResult.VendorID);
                    foreach (var selectVendorByIdResult in vendor)
                    {
                        lblVendor.Text = selectVendorByIdResult.Address1;
                    }
                }
            }


            DataList DLCouponsList = e.Item.FindControl("DLCouponsList") as DataList;
            


            if (ViewState["Type"].ToString() == "Available") {
                var CouponsList = Deal.select_CouponsCodeUsedAvailable(Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "OrderID")), Convert.ToBoolean(0));
                DLCouponsList.DataSource = CouponsList;
                DLCouponsList.DataBind();

            }
            if (ViewState["Type"].ToString() == "Used") {
                var CouponsList = Deal.select_CouponsCodeUsedAvailable(Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "OrderID")), Convert.ToBoolean(1));
                DLCouponsList.DataSource = CouponsList;
                DLCouponsList.DataBind();
            }
            if (ViewState["Type"].ToString() == "All") {
                var CouponsList = Deal.select_CouponsCode(Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "OrderID")));
                DLCouponsList.DataSource = CouponsList;
                DLCouponsList.DataBind();
            }
        }
    }
    protected void Gift_ItemDataBound(object sender, GridItemEventArgs e) {

        if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem) {
            DataList DLCouponsList = e.Item.FindControl("GiftDLCouponsList") as DataList;
            var Deal = new DealesDataContext();
            var CouponsList = Deal.select_CouponsCode(Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "OrderID")));
            DLCouponsList.DataSource = CouponsList;
            DLCouponsList.DataBind();

        }
    }
    protected void lblNAme_OnClick(object sender, EventArgs e) {
        LinkButton lnkbtn = (LinkButton)sender;
        Response.Redirect("~/Default.aspx?RecentDealID=" + lnkbtn.CommandArgument);
    }
    protected void Image1_OnClick(object sender, EventArgs e) {
        ImageButton imgbtn = (ImageButton)sender;
        Response.Redirect("~/Default.aspx?RecentDealID=" + imgbtn.CommandArgument);
    }
    protected void btnUpload_OnClick(object sender, EventArgs e) {

        Byte[] bytes = null;
        if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "") {
            Stream fs = FileUpload1.PostedFile.InputStream;
            BinaryReader br = new BinaryReader(fs);
            bytes = new Byte[(Int32)fs.Length + 1];
            bytes = br.ReadBytes((Int32)fs.Length);

            var img = new DealesDataContext();
            var ImageChangeQuery = img.Update_UserImage(Convert.ToString(ViewState["UserID"]), bytes);

        }
    }
    protected void btnPasswordChange_OnClick(object sender, EventArgs e) {
        if (txtPasswordChange.Text == "" || txtConfirmPassword.Text == "") {
            lblPasswordError.Text = "Please enter the passord";
            divPassword.Style.Remove("Display");
            return;
        }
        if (!txtPasswordChange.Text.Equals(txtConfirmPassword.Text)) {
            lblPasswordError.Text = "Password doesn't match confirmation password";
            divPassword.Style.Remove("Display");
            return;
        }
        Membership.GetUser().ChangePassword(Membership.GetUser().GetPassword(), txtPasswordChange.Text);
        txtPasswordChange.Text = "";
        txtConfirmPassword.Text = "";
        divPassword.Style.Add("Display", "None");
    }
    protected void btnEditName_OnClick(object sender, EventArgs e) {
        var name = new DealesDataContext();
        var NameChangeQuery = name.Update_UserName(Convert.ToString(ViewState["UserID"]), txtFirstName.Text, txtLastName.Text);
    }
    protected void Page_Prerender(object sender, EventArgs e) {
        try {
            if (ViewState["UserID"] != null) {
                imgDefault.ImageUrl = "../GetImage.aspx?UserID=" + ViewState["UserID"].ToString();
                var name = new DealesDataContext();
                var ChangeUpdatedNameQuery = name.Select_UserName(ViewState["UserID"].ToString());
                foreach (var item in ChangeUpdatedNameQuery) {
                    lblFullName.Text = item.FirstName.ToString() + " " + item.LastName.ToString();
                }
            }
        } catch {
        }

    }
    protected void btnUpdateImage_OnClick(object sender, EventArgs e) {
        divAvatar.Style.Remove("Display");
    }
    protected void btnUpdateFullName_OnClick(object sender, EventArgs e) {
        var name = new DealesDataContext();
        var ChangeUpdatedNameQuery = name.Select_UserName(Membership.GetUser().ProviderUserKey.ToString());
        foreach (var item in ChangeUpdatedNameQuery) {
            txtFirstName.Text = item.FirstName.ToString();
            txtLastName.Text = item.LastName.ToString();
        }
        divName.Style.Remove("Display");
    }
    protected void btnUpdateEmailNotification_OnClick(object sender, EventArgs e) {
        divEmailNote.Style.Remove("Display");
    }
}
